﻿mainModule.controller('BaseEditCtrl', ["$scope", "$rootScope", "baseEvents", "apiSvc", function ($scope, $rootScope, baseEvents, apiSvc) {
    "use strict";
    var events = baseEvents($scope.entityName);
    $scope.events = events;
    var mode;

    hide();

    function hide() {
        $scope.isVisible = false;
    }
    function show() {
        $scope.isVisible = true;
    }

    $scope.onEditingEvent = function (e, id) {
        mode = "edit";
        show();
        apiSvc.findById(id).then(function (response) {
            $scope.item = response.data;
        });
    }
        
    $scope.onAddingEvent = function (e) {
        mode = "add";
        show();
        $scope.item = {};
    }

    $scope.cancel = function () {
        hide();
    }

    $scope.save = function () {
        if ($scope.editForm.$valid) {
            if (mode === "edit") {
                apiSvc.edit($scope.item).then(function (response) {
                    if (response.data.Success) {
                        $scope.$emit(events.editedEvent, $scope.item);
                        hide();
                    }                                                
                });
            }
            else {
                apiSvc.add($scope.item).then(function (response) {
                    if (response.data.Success) {
                        $scope.item.Id = response.data.Value;
                        $scope.$emit(events.addedEvent, $scope.item);
                        hide();
                    }                                                
                });
            }
        }
    }

    $scope.$on(events.editingEvent, function (e, id) {
        $scope.onEditingEvent(e, id);
    });

    $scope.$on(events.addingEvent, function (e) {
        $scope.onAddingEvent(e);
    });

    $scope.$on(events.searchingEvent, function (e) {
        hide();
    });

    $scope.$on(events.removingEvent, function (e) {
        hide();
    });
}]);


                
            
